package com.app.community.controller;

import com.app.community.exception.ErrorCodeEnum;
import com.app.community.service.LoginService;
import com.wordnik.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * 登陆页面
 * @Date 2020/10/9 23:53
 **/
@Slf4j
@Controller
public class LoginController {

    @Autowired
    LoginService loginService;

    @ApiOperation("访问主页")
    @GetMapping(path = "login")
    public String login(Model model, HttpSession httpSession) {
        // 用户session不为空,则不允许重复登陆
        if (httpSession.getAttribute("userId") != null ){
            model.addAttribute("signal",1);
            model.addAttribute("error",ErrorCodeEnum.LOGINREPEATLY.getDescription());
            return "common/login";
        }
        return "common/login";
    }

    @ApiOperation("登陆验证")
    @PostMapping(path = "login")
    public String login(@RequestParam("userId") String userId, @RequestParam("password") String password, Model model, HttpSession httpSession) {
        model.addAttribute("userId",userId);
// 使用shiro进行登录验证
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userId, password);

        try {
            subject.login(token);
        } catch (UnknownAccountException ae) {
            model.addAttribute("error", ErrorCodeEnum.USERNOTEXIST.getDescription());
            return "common/login";
        }catch (AuthenticationException ae){
            model.addAttribute("error",ErrorCodeEnum.AUTHENTICERROR);
            return "common/login";
        }
        if (subject.isAuthenticated()) {
            // 用户ID加入session
            httpSession.setAttribute("userId",userId);

            return "redirect:index";
        } else {
            return "common/login";
        }

    }
}


